import os
import yaml
import re
from collections import Counter

def load_prompt_templates():
    """加载提示词模板"""
    try:
        with open(os.path.join(os.path.dirname(__file__), r'F:\AI_Learn\AI_Werewolf\M2H\prompt.yaml'), 'r', encoding='utf-8') as f:
            return yaml.safe_load(f) or {}
    except FileNotFoundError:
        print("警告: 找不到prompt.yaml文件")
        return {}
    except Exception as e:
        print(f"警告: 加载prompt.yaml文件时出错: {e}")

        return {}


def get_formatted_prompt(player_name, role, player_count):
    # 加载模板
    templates = load_prompt_templates()

    # 获取游戏模板
    game_rules = templates['game_rules']
    formatted_game_rules = game_rules.format(
        player_count=player_count
    )

    # 获取角色模板
    role_template = templates['role_templates'][f'{role}']
    # 替换角色模板中的占位符
    formatted_role_prompt = role_template.format(
        player_name=player_name
    )

    # 生成最终提示词
    final_prompt = templates['final_prompt'].format(
        game_rules=formatted_game_rules,
        role_prompt=formatted_role_prompt
    )

    return final_prompt


def find_most_frequent_vote(votes):
    """用于统计投票数量"""  
    # 提取每个投票中的数字
    numbers = []
    for vote in votes:
        # 使用正则表达式找到所有数字
        vote_str = str(vote)
        match = re.search(r'\d+', vote_str)
        if match:
            numbers.append(match.group())

    if not numbers:
        return "弃权", None

    # 统计数字出现的次数
    count = Counter(numbers)

    # 找到出现次数最多的数字
    most_common = count.most_common(1)[0]
    return int(most_common[0]), most_common[1]

def find_most_frequent_kill(votes):
    # 统计数字出现的次数
    count = Counter(votes)

    # 找到出现次数最多的数字
    most_common = count.most_common(1)[0]
    return int(most_common[0]), most_common[1]

def extract_number_from_string(s):
    match = re.search(r'投票:(\d+)号', s)

    if match:
        # 提取匹配到的数字并转换为整数
        return int(match.group(1))
    else:
        # 如果没有找到数字，返回None或提示信息
        return '弃权'

def extract_kill_from_string(s):
    match = re.search(r'选择击杀:?(\d+)号', s)

    if match:
        # 提取匹配到的数字并转换为整数
        return int(match.group(1))
    else:
        # 如果没有找到数字，返回None或提示信息
        return None
